package cn.com.api.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.com.api.entity.ApiDianPing;
import cn.com.api.requestpage.DianPingPage;
import cn.com.api.service.ApiDianPingService;
import cn.com.api.service.ApiOrderService;
import cn.com.api.service.CheckService;
import cn.com.util.*;

@Controller
@RequestMapping(Utils.SYS_API + "dianping/")
public class ApiDianPingController {
	@Autowired
	private ApiDianPingService dianPingService;
	@Autowired
	private ApiOrderService apiOrderService;
	@Autowired
	private CheckService checkService;

	private static Logger logger = Logger
			.getLogger(ApiDianPingController.class);

	/** ---------------商铺端 -------------------------------- */

	/**
	 * 条件查询对商家的点评 评分及数量
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/searchDianPingSumByShopid")
	public void searchDianPingSumBySid(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String shop_id = request.getParameter("shop_id");
			String token = request.getParameter("token");
			Map<String, String> params = new HashMap<String, String>();
			params.put("shop_id", shop_id);
			params.put("token", token);
			if (checkService.checkToken(shop_id, token, map)
					&& checkService.checkParams(params, map)) {
				dianPingService.searchDianPingSumInfoByShopid(params, map);
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 条件查询对商家评价列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/searchDianPingByShopid")
	public void searchDianPingBySid(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String shop_id = request.getParameter("shop_id");
			String pageCount = request.getParameter("pageCount");
			String type = request.getParameter("type");
			String token = request.getParameter("token");
			Map<String, String> params = new HashMap<String, String>();
			params.put("shop_id", shop_id);
			params.put("pageCount", pageCount);
			params.put("type", type);
			params.put("token", token);
			if (checkService.checkToken(shop_id, token, map)
					&& checkService.checkParams(params, map)) {
				dianPingService.searchDianPingByShopid(params, map);
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 商家回复订单的评价
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/replyOrderEvaluate")
	public void replyOrderEvaluate(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String shop_id = request.getParameter("shop_id");
			String orderId = request.getParameter("orderId");
			String content = request.getParameter("content");
			String token = request.getParameter("token");
			Map<String, String> params = new HashMap<String, String>();
			params.put("shop_id", shop_id);
			params.put("orderId", orderId);
			params.put("content", content);
			params.put("token", token);
			if (checkService.checkToken(shop_id, token, map)
					&& checkService.checkParams(params, map)) {
				dianPingService.replyOrderEvaluate(params, map);
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/** ------------------------客户端------------------------------- **/

	/**
	 * 条件查询对商品的点评 评分 及数量
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/searchDianPingSumByGoodsid")
	public void searchDianPingSumByGoodsid(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String good_id = request.getParameter("goods_id");
			Map<String, String> params = new HashMap<String, String>();
			params.put("goods_id", good_id);
			if (checkService.checkParams(params, map)) {
				dianPingService.searchDianPingSumInfoByGoodsid(params, map);
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 条件查询对商品的点评列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/searchDianPingByGoodsid")
	public void searchDianPingByGoodsid(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String good_id = request.getParameter("goods_id");
			String pageCount = request.getParameter("pageCount");
			String type = request.getParameter("type");
			Map<String, String> params = new HashMap<String, String>();
			params.put("goods_id", good_id);
			params.put("pageCount", pageCount);
			params.put("type", type);
			if (checkService.checkParams(params, map)) {
				dianPingService.searchDianPingByGoodsid(params, map);
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	// 客户端查询 店铺 的评价信息 不需要token shop_id
	/**
	 * 条件查询对商家的点评 评分及数量
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/searchShopDianPingSumByShopid")
	public void searchShopDianPingSumBySid(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String shop_id = request.getParameter("shop_id");
			Map<String, String> params = new HashMap<String, String>();
			params.put("shop_id", shop_id);
			if (checkService.checkParams(params, map)) {
				dianPingService.searchDianPingSumInfoByShopid(params, map);
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 条件查询对商家评价列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/searchShopDianPingByShopid")
	public void searchShopDianPingBySid(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String shop_id = request.getParameter("shop_id");
			String pageCount = request.getParameter("pageCount");
			String type = request.getParameter("type");
			Map<String, String> params = new HashMap<String, String>();
			params.put("shop_id", shop_id);
			params.put("pageCount", pageCount);
			params.put("type", type);// 1-未回复的差评 2-未回复 0-全部 3-好评 4-差评
			if (checkService.checkParams(params, map)) {
				dianPingService.searchDianPingByShopid(params, map);
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 待评价的商品-----已完成的订单，待评价
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/searchNoDianPingOrders")
	public void searchNoDianPingOrders(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String u_id = request.getParameter("u_id");// 查询已完成的订单，待评价
			String pageCount = request.getParameter("pageCount");// 查看的当前页
			String token = request.getParameter("token");
			PageInfo page = new PageInfo();
			page.setCurrentPage(Integer.parseInt(pageCount));// 设置要读取的页
			Map<String, String> params = new HashMap<String, String>();
			params.put("u_id", u_id);
			params.put("token", token);
			if (checkService.checkToken(u_id, token, map)
					&& checkService.checkParams(params, map)) {
				apiOrderService.getNoDianPingOrders(params, map, page);
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.write(JsonUtil.object2json(map));
		out.close();
	}

	/**
	 * 添加订单评价
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("addDianPingToOrder")
	public void addDianPingToOrder(DianPingPage dianPingPage,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		String u_id = dianPingPage.getU_id();
		String token = dianPingPage.getToken();
		try {
			if (checkService.checkToken(u_id, token, map)
					&& checkService.checkDianPing(dianPingPage, map)) {
				dianPingService.addDianPingToOrder(dianPingPage);
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "评价成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}

		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.write(JsonUtil.object2json(map));
		out.close();
	}
	
	
	
	/**
	 * 添加或修改订单评价
	 * @author JW
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("addOrUpdDianPing")
	public void addOrUpdDianPing(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String cId=request.getParameter("cId");//评论标识id
			List<String> prodList=new ArrayList<>();
			String [] productIds=request.getParameter("productId").split(",");
			
			String [] cDtypes=request.getParameter("cDtype").split(",");
			String [] cTexts=request.getParameter("cText").split("WECANNOTGETERRORCODE");
			String cIp=request.getParameter("cIp");
			String cUserId=request.getParameter("cUserId");
			String orderNum=request.getParameter("orderNum");
			
			List<ApiDianPing> list=new ArrayList<>();
			ApiDianPing apiDianPing=null;
			if (!Util.isNull(productIds)) {
				for (int i = 0; i < productIds.length; i++) {
					apiDianPing=new ApiDianPing();
					apiDianPing.setC_ip(cIp);//主机IP
					apiDianPing.setC_userid(cUserId);
					apiDianPing.setC_appdate(DateUtil.nowTimeToString());//添加时间
					apiDianPing.setC_orderid(orderNum);//订单编号
					apiDianPing.setIs_reply(0);//商家是否回复 0 否 1 是
					apiDianPing.setC_goodsid(Long.valueOf(productIds[i]));
					apiDianPing.setC_dtype(Integer.parseInt(cDtypes[i]));
					apiDianPing.setC_text(cTexts[i]);
					list.add(apiDianPing);
					prodList.add(productIds[i]);
				}
				dianPingService.batchInsert(list);
			}
			
			if (Util.isNull(cId)) {
				int num=0;
				String otherProductIds=apiOrderService.getProductIdsByOrderNum(orderNum,prodList);
				if (!Util.isNull(otherProductIds)) {
					String allproductId[]= otherProductIds.split(",");
					for (int i = 0; i < productIds.length; i++) {
						if (Util.isNull(dianPingService.getDianPingByCondition(orderNum, allproductId[i]))) {
							num++;
							break;
						}
					}
				}
				if (num==0) {
					apiOrderService.updPlStatusByOrderNum(orderNum);
				}
				//dianPingService.addDianPing(apiDianPing);
			}else {
				//apiDianPing.setC_id(Integer.parseInt(cId));
				//dianPingService.updDianPing(apiDianPing);
			}
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "操作成功");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}
	
	
	
	/**
	 * 商户评论
	 * @author JW
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("replyDianPing")
	public void replyDianPing(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String cId=request.getParameter("cId");//评论标识id
			//String productId=request.getParameter("productId");
			//String orderNum=request.getParameter("orderNum");
			
			String reText=request.getParameter("reText");
			//reText = new String(reText.getBytes("ISO-8859-1"), "utf-8");
			ApiDianPing apiDianPing=new ApiDianPing();
			
			String nowTimeString=DateUtil.nowTimeToString();
			//if (!Util.isNull(productId)) {
			//	apiDianPing.setC_goodsid(Long.valueOf(productId));//货品id
			//}
			apiDianPing.setC_id(Integer.parseInt(cId));
			//apiDianPing.setC_orderid(orderNum);//订单编号
			apiDianPing.setC_retext(reText);//回复内容
			apiDianPing.setC_redate(nowTimeString);//回复时间
			apiDianPing.setIs_reply(1);
			dianPingService.replyDianPing(apiDianPing);
			
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "操作成功");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(Util.getStackTraceAsString(e));
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}
	
	
}
